import {Alert, Button, Card, Form, Image, Input, Modal, Popconfirm, Space, Table, Tabs, Upload, message} from "antd";
import './edit.less'
import {CheckCircleOutlined, CloseCircleOutlined, DeleteOutlined, EditOutlined} from "@ant-design/icons";
import {useEffect, useState} from "react";
import ImgCrop from "antd-img-crop";
import EditModal from "./EditModal/EditModal";
import http from "../../../utils/http";

const Edit = (props)=>{
    const [swiperVisible,setSwiperVisible] = useState(false);
    const [menuVisible,setMenuVisible] = useState(false);
    const [navVisible,setNavVisible] = useState(false);
    const [swiperData,setSwiperData] = useState({
        name:'',
        photo:'',
        url:'',
        state:'',
        sort:''
    });
    const [menuData,setMenuData] = useState({
        name:'',
        photo:'',
        url:'',
        state:'',
        sort:''
    });
    const [name,setName] = useState('');
    const [navId,setNavId] = useState('');
    const [navUnchecked,setNavUnchecked] = useState('');
    const [navChecked,setNavChecked] = useState('');
    const [navEditData,setNavEditData] = useState({
        name:'',
        photoOne:'',
        photoTwo:''
    });
    const [checkedCropImg,setCheckedCropImg] = useState([]);
    const [uncheckedCropImg,setUncheckedCropImg] = useState([]);
    const [previewVisible,setPreviewVisible] = useState(false);
    const [previewImg,setPreviewImg] = useState('');

    const [swiperModal1,setSwiperModal] = useState();
    const [menuModal1,setMenuModal] = useState();

    const {TabPane} = Tabs;
    const [form] = Form.useForm();

    let editData = JSON.parse(JSON.stringify(navEditData));

    useEffect(()=>{
        setMenuModal(menuModal());
        setSwiperModal(swiperModal());
    },[swiperVisible,menuVisible])

    let swiper = props.swiper;
    let menu = props.menu;
    let nav = props.nav;

    const swiperColumns = [
        {
            title:'名称',
            dataIndex: 'name',
            key: 'name',
            align:'center'
        },
        {
            title:'缩略图片',
            dataIndex: 'photo',
            key: 'photo',
            align:'center',
            render: (text,record)=> {
                return (
                    <Image width={50} src={record.photo} />
                )
            }
        },
        {
            title:'区块链接',
            dataIndex: 'url',
            key: 'url',
            align:'center',
            render:(text,record)=>(
                <div className={'edit-url'} title={record.url}>{record.url}</div>
            )
        },
        {
            title:'状态',
            dataIndex: 'state',
            key: 'state',
            align:'center',
            render:(text,record)=>{
                if(record.state){
                    return (
                        <CheckCircleOutlined style={{color:'green'}} />
                    )
                }else {
                    return (
                        <CloseCircleOutlined style={{color:'red'}} />
                    )
                }
            }
        },
        {
            title:'排序',
            dataIndex: 'sort',
            key: 'sort',
            align:'center'
        },
        {
            title:'操作',
            dataIndex: 'operation',
            key: 'operation',
            align:'center',
            render:(text,record)=>{
                return (
                    <span>
                        <Button type={'link'} onClick={swiperEdit.bind(this,record)} ><EditOutlined /></Button>
                        <Popconfirm title="确定删除吗？" okText="删除" cancelText="取消" onConfirm={confirmSwiperDelete.bind(this,record)}>
                            <Button type={'link'} ><DeleteOutlined /></Button>
                        </Popconfirm>
                    </span>
                )
            }
        },
    ];
    const menuColumns = [
        {
            title:'名称',
            dataIndex: 'name',
            key: 'name',
            align:'center'
        },
        {
            title:'缩略图片',
            dataIndex: 'photo',
            key: 'photo',
            align:'center',
            render: (text,record)=> {
                return (
                    <Image width={50} src={record.photo} />
                )
            }
        },
        {
            title:'区块链接',
            dataIndex: 'url',
            key: 'url',
            align:'center',
            render:(text,record)=>(
                <div className={'edit-url'} title={record.url}>{record.url}</div>
            )
        },
        {
            title:'状态',
            dataIndex: 'state',
            key: 'state',
            align:'center',
            render:(text,record)=>{
                if(record.state){
                    return (
                        <CheckCircleOutlined style={{color:'green'}} />
                    )
                }else {
                    return (
                        <CloseCircleOutlined style={{color:'red'}} />
                    )
                }
            }
        },
        {
            title:'排序',
            dataIndex: 'sort',
            key: 'sort',
            align:'center'
        },
        {
            title:'操作',
            dataIndex: 'operation',
            key: 'operation',
            align:'center',
            render:(text,record)=>{
                return (
                    <span>
                        <Button type={'link'} onClick={menuEdit.bind(this,record)}><EditOutlined /></Button>
                        <Popconfirm title="确定删除吗？" okText="删除" cancelText="取消" onConfirm={confirmMenuDelete.bind(this,record)}>
                            <Button type={'link'} ><DeleteOutlined /></Button>
                        </Popconfirm>
                    </span>
                )
            }
        },
    ];
    const navColumns = [
        {
            title:'名称',
            dataIndex: 'name',
            key: 'name',
            align:'center'
        },{
            title:'选中图片',
            dataIndex: 'photoOne',
            key: 'photoOne',
            align:'center',
            render: (text,record)=> {
                return (
                    <Image width={50} src={record.photoOne} />
                )
            }
        },{
            title:'未选图片',
            dataIndex: 'photoTwo',
            key: 'photoTwo',
            align:'center',
            render: (text,record)=> {
                return (
                    <Image width={50} src={record.photoTwo} />
                )
            }
        },{
            title:'操作',
            dataIndex: 'operation',
            key: 'operation',
            align:'center',
            render:(text,record)=>{
                return (
                    <span>
                        <Button type={'link'} onClick={navEdit.bind(this,record)}><EditOutlined /></Button>
                    </span>
                )
            }
        }
    ];

    function callback() {
        console.log(props);
    }

    const confirmSwiperDelete = (record)=>{
        console.log(record);
        http({
            url:'api/diyController/bannerDelete',
            method:'post',
            data:{id:record.id}
        }).then(res=>{
            if(res.code == 200){
                message.success('删除成功');
                props.onData(111);
            }else {
                message.error('删除失败');
            }
        }).catch(err=>{
            console.log(err);
        })
    }
    const confirmMenuDelete = (record)=>{
        http({
            url:'api/diyController/controlTableDelete',
            method:'post',
            data:{id:record.id}
        }).then(res=>{
            if(res.code == 200){
                message.success('删除成功');
                props.onData(111);
            }else {
                message.error('删除失败');
            }
        }).catch(err=>{
            console.log(err);
        })
        console.log(record);
    }

    const openSwiperModal = ()=> {
        setSwiperData({
            name:'',
            photoOne:'',
            photoTwo:''
        });
        setSwiperVisible(true);
    }

    const closeNavModal = ()=>{
        setNavVisible(false);
    }
    const submitNavModal =()=>{
        http({
            url:'api/diyController/navigationUpdate',
            method:'post',
            data: {
                id:navId,
                name:name,
                photoOne:navUnchecked,
                photoTwo:navChecked
            }
        }).then(res=>{
            console.log(res)
            if(res.code == 200){
                message.success('修改成功');
                props.onData(111);
                setNavVisible(false);
            }else {
                message.warning('修改失败');
            }
        })
    }

    //添加图片是调用
    const onCheckedChange = (ev) => {
        setCheckedCropImg(ev.fileList);
        if(ev.fileList[0].status == 'uploading'){
            editData.name = name;
            form.setFieldsValue(editData);
        }
        if(ev.fileList[0].status == 'done'){
            console.log(ev.fileList[0].status)
            editData.photoOne = ev.fileList[0].response.relativePath;
            editData.name = name;
            form.setFieldsValue(editData);
            setNavChecked(ev.fileList[0].response.relativePath);
            console.log(editData)
        }
    };
    const onUncheckedChange = (ev) => {
        setUncheckedCropImg(ev.fileList);
        if(ev.fileList[0].status == 'uploading'){
            editData.name = name;
            form.setFieldsValue(editData);
        }
        if(ev.fileList[0].status == 'done'){
            editData.photoTwo = ev.fileList[0].response.relativePath;
            editData.name = name;
            form.setFieldsValue(editData);
            setNavUnchecked(ev.fileList[0].response.relativePath)
            console.log(editData)
        }
    };

    const onPreview = async file => {
        setPreviewImg(file.url);
        setName(editData.name);
        setPreviewVisible(true);
    };

    const handleCancel = ()=>{
        setPreviewVisible(false)
    }

    const swiperEdit = (record)=>{
        setSwiperData(record);
        setSwiperVisible(true);
    }
    const menuEdit = (record)=>{
       setMenuData(record);
        setMenuVisible(true);
    }
    const navEdit = (record)=>{
        editData = record;
        setNavId(record.id);
        setCheckedCropImg([{
            name:'checkedImage.png',
            status:'done',
            url:record.photoOne
        }]);
        setUncheckedCropImg([{
            name:'uncheckedImage.png',
            status:'done',
            url:record.photoTwo
        }]);
        setName(editData.name);
        setNavVisible(true);
        form.setFieldsValue(editData);
        console.log('name',name)
    }

    const getSwiperVisible = (msg)=>{
        setSwiperVisible(msg);
    }
    const getMenuVisible = (msg)=>{
        setMenuData({
            name:'',
            photoOne:'',
            photoTwo:''
        });
        setMenuVisible(msg);
    }
    const openMenuModal = ()=> {
        setMenuVisible(true);
    }

    const swiperCrop = {
        width: 355,  //裁剪宽度
        height: 180, //裁剪高度
        aspect: 71/36, //剪裁比例
        minZoom: 1, //最小倍数
        maxZoom: 10, //最大倍数
        resize: false, //裁剪是否可以调整大小
        resizeAndDrag: true, //裁剪是否可以调整大小、可拖动
        modalTitle: "上传轮播图", //弹窗标题
        modalWidth: 600, //弹窗宽度
        modalOk: '上传',
        modalCancel: '取消'
    };

    const menuCrop = {
        width: 100,  //裁剪宽度
        height: 100, //裁剪高度
        aspect: 1, //剪裁比例
        minZoom: 1, //最小倍数
        maxZoom: 10, //最大倍数
        resize: false, //裁剪是否可以调整大小
        resizeAndDrag: true, //裁剪是否可以调整大小、可拖动
        modalTitle: "上传功能图", //弹窗标题
        modalWidth: 600, //弹窗宽度
        modalOk: '上传',
        modalCancel: '取消',
    };

    const navCrop = {
        width: 100,  //裁剪宽度
        height: 100, //裁剪高度
        aspect: 1, //剪裁比例
        minZoom: 1, //最小倍数
        maxZoom: 10, //最大倍数
        resize: false, //裁剪是否可以调整大小
        resizeAndDrag: true, //裁剪是否可以调整大小、可拖动
        modalTitle: "上传菜单栏", //弹窗标题
        modalWidth: 600, //弹窗宽度
        modalOk: '上传',
        modalCancel: '取消',
    };

    const setData = (type,data) => {
            props.onData(11111)
    }

    const menuModal = () => (
        <EditModal
            type={'menu'}
            thisData={menu}
            visibleModal={menuVisible}
            imgCropStyle={menuCrop}
            changeVisible={getMenuVisible}
            editData={menuData}
            image={menuData.photo}
            onData={setData}/>
    )
    const swiperModal = () => (
        <EditModal
            type={'swiper'}
            thisData={swiper}
            visibleModal={swiperVisible}
            imgCropStyle={swiperCrop}
            changeVisible={getSwiperVisible}
            editData={swiperData}
            image={swiperData.photo}
            onData={setData}/>
    )

    return (
        <Card className={'edit-card'}>
            <Tabs style={{width:'100%'}} centered={true} defaultActiveKey="1" onChange={callback}>
                <TabPane tab="轮播图" key="1">
                    <div>
                        <Button type={'normal'} style={{background:'black',color:'white'}} shape={'round'} onClick={openSwiperModal}>新增轮播图</Button>
                    </div>
                    <Alert style={{fontSize:'12px'}} message="轮播图尺寸大小：355*180" type="warning" closable />
                    <Table dataSource={swiper} columns={swiperColumns} pagination={{ position: ['none', 'none'] }} />
                    {swiperModal1}
                </TabPane>
                <TabPane tab="功能栏" key="2">
                    <div>
                        <Button type={'normal'} style={{background:'black',color:'white'}} shape={'round'} onClick={openMenuModal}>新增功能栏</Button>
                    </div>
                    <Alert style={{fontSize:'12px'}} message="功能图尺寸：100*100   最多显示10个功能分类" type="warning" closable />
                    <Table dataSource={menu} columns={menuColumns} pagination={{ position: ['none', 'none'] }} />
                    {menuModal1}
                </TabPane>
                <TabPane tab="导航栏" key="3">
                    <Alert style={{fontSize:'12px'}} message="导航栏icon尺寸：100*100，必须添加选中和未选图片" type="warning" closable />
                    <Table dataSource={nav} columns={navColumns} pagination={{ position: ['none', 'none'] }} />
                    <Modal className={'edit-modal-submit'}
                           title="新增功能分类"
                           getContainer={false}
                           visible={navVisible}
                           footer={[
                               <Button key="back" onClick={closeNavModal}>
                                   取消
                               </Button>,
                               <Button key="submit" style={{background:'black',color:'white'}} onClick={submitNavModal}>
                                   修改
                               </Button>
                           ]}
                           onCancel={closeNavModal}>
                        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} form={form} initialValues={editData}>
                            <Form.Item
                                label="名称"
                                name="name"
                                rules={[{ required: true, message: '请输入区块名！' }]}
                            >
                                <Input
                                    placeholder={'请输入区块链接名称'}
                                    value={editData.name}
                                    onChange={(ev)=>{editData.name = ev.target.value;setName(ev.target.value)}} />
                            </Form.Item>
                            <Form.Item
                                label="区块链接"
                                name="url"
                                rules={[{ required: true, message: '请输入区块链接路径！' }]}
                            >
                                <Space direction="vertical" size={'middle'} style={{width:'100%'}}>
                                    <ImgCrop {...navCrop}>
                                        <Upload
                                            action="api/uploadFile/oss" /*上传地址*/
                                            listType="picture-card"
                                            fileList={checkedCropImg}
                                            maxCount={1}
                                            onChange={onCheckedChange}
                                            onPreview={onPreview}
                                        >
                                            {checkedCropImg.length ? checkedCropImg.length < 2 && '+ 上传图片' : '+ 上传图片'}
                                        </Upload>
                                    </ImgCrop>
                                </Space>
                            </Form.Item>
                            <Form.Item
                                label="排序"
                                name="sort"
                                rules={[{ required: true, message: '请输入区块排序！' }]}
                            >
                                <Space direction="vertical" size={'middle'} style={{width:'100%'}}>
                                    <ImgCrop {...navCrop}>
                                        <Upload
                                            action="/api/uploadFile/oss" /*上传地址*/
                                            listType="picture-card"
                                            fileList={uncheckedCropImg}
                                            maxCount={1}
                                            onChange={onUncheckedChange}
                                            onPreview={onPreview}
                                        >
                                            {uncheckedCropImg.length ? uncheckedCropImg.length < 2 && '+ 上传图片' : '+ 上传图片'}
                                        </Upload>
                                    </ImgCrop>
                                </Space>
                            </Form.Item>
                        </Form>
                        <Modal
                            visible={previewVisible}
                            title={'查看图片'}
                            footer={null}
                            onCancel={handleCancel}
                        >
                            <img alt="example" style={{ width: '100%' }} src={previewImg} />
                        </Modal>
                    </Modal>
                </TabPane>
            </Tabs>
        </Card>
    )
}

export default Edit;